﻿

// 创建侧边栏容器
const sidebar = document.createElement('div');
sidebar.id = 'custom-sidebar';

// 聊天界面结构
sidebar.innerHTML = `
  <div id="drag-handle"></div>
  <div class="chat-container">
    <div class="message-box" id="message-box"></div>
    <div class="input-area">
      <textarea id="input-field" placeholder="输入消息..."></textarea>
      <button id="send-btn">发送</button>
      <button id="refresh">刷新</button>
      <button id="refresh1">刷新</button>
    </div>
  </div>
`;

document.body.appendChild(sidebar);

// 聊天功能实现
const messageBox = document.getElementById('message-box');
const inputField = document.getElementById('input-field');
const sendBtn = document.getElementById('send-btn');
const refreshBtn = document.getElementById('refresh');
const dragHandle = document.getElementById('drag-handle');

// 添加消息到对话框
function addMessage(content, isUser = true) {
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${isUser ? 'user' : 'bot'}`;

  const formattedContent = content.replace(/###\s+(.+)/g, '<br><strong>$1</strong>'); // 将 ### 后面的文本换行并加粗
    
  const linkRegex = /\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g;
  const formattedContent2 = formattedContent.replace(linkRegex, '<a href="$2" target="_blank">$1</a>');


  // 将解析后的内容插入到消息框中
  messageDiv.innerHTML = formattedContent2;
  messageBox.appendChild(messageDiv);
  messageBox.scrollTop = messageBox.scrollHeight;
}

// 提取页面内容
function extractContent() {
  let xpath = "//div[@id='description-val']/div[@class='je_rdata_container je_html']/div[@class='je_rdata']"
  let result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  if (result.snapshotLength === 0) 
  {
    xpath = "//div[@id='description-val']//div[@class='je_rdata']";
    result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  }
  let content = '';
  for (let i = 0; i < result.snapshotLength; i++) {
    console.log(result.snapshotItem(i).textContent);
    content += result.snapshotItem(i).textContent + '\n';
  }
  return content.trim();
}

async function callAIAPI(sprompt) {
  const apiUrl = `https://dashscope.aliyuncs.com/api/v1/apps/398b7c586d684fa6b372f0b0b7c705b0/completion`;

  const requestBody = { 
    input: { prompt: sprompt }, 
    parameters:  {},
    debug: {}
  }; 
  console.log(JSON.stringify(requestBody));  

  const response = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer sk-99a5599608914adcb6cb67bd33f31e37`
    },
    body: JSON.stringify(requestBody)
  });

  if (!response.ok)  { 
    const errorText = await response.text();  
    throw new Error(`API请求失败，状态码：${response.status} ，错误信息：${errorText}`); 
  } 

  const data = await response.json();
  
    console.log(data.output.text);  
    return new Promise(resolve => {
    setTimeout(() => {
      resolve(data.output.text);
    }, 800);
  });
  // 根据实际API响应结构调整返回路径，示例：
  // return data.output.text; // 如果阿里云返回结构不同
  // return data.choices[0].message.content; // 保持原结构，根据实际调试修改
}

// 发送消息处理
async function handleSend(prompt) {
  if (!prompt) return;

  addMessage(prompt, true);
  inputField.value = '';
  
  // 添加等待状态
  const waitingDiv = document.createElement('div');
  waitingDiv.className = 'message loading';
  waitingDiv.textContent = '正在思考中...';
  messageBox.appendChild(waitingDiv);
  
  try {
    const response = await callAIAPI(prompt);
    messageBox.removeChild(waitingDiv);
    addMessage(response, false);
  } catch (error) {
    messageBox.removeChild(waitingDiv);
    addMessage(`请求失败：${error.message}`, false);
  }
}

async function handleRefresh() {
  // 清空对话框，并且重新发起initchat
    messageBox.innerHTML = '';

    const extractedContent = extractContent();
    if (extractedContent) {
      const initialPrompt = `请根据以下内容回答问题：\n\n${extractedContent}`;
      handleSend(initialPrompt);
    } else {
      addMessage('未找到相关内容，请手动输入问题。', false);
    }
}

// 页面加载后自动提取内容并提问
function initChat() {
  // const extractedContent = extractContent();
  // if (extractedContent) {
  //   const initialPrompt = `请根据以下内容回答问题：\n\n${extractedContent}`;
  //   handleSend(initialPrompt);
  // } else {
  //   addMessage('未找到相关内容，请手动输入问题。', false);
  // }
}

// 事件监听
sendBtn.addEventListener('click', () => handleSend(inputField.value.trim()));
refreshBtn.addEventListener('click', () => handleRefresh());
inputField.addEventListener('keydown', (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    handleSend(inputField.value.trim());
  }
});

dragHandle.addEventListener('dblclick', () => { // 双击拖动句柄隐藏或显示侧边栏
  if (sidebar.style.width === '0px' || sidebar.style.width === '') {
    sidebar.style.width = '350px'; // 显示侧边栏
  } else {
    sidebar.style.width = '0px'; // 隐藏侧边栏
  }
});


// 初始化
// initChat();

// 拖动功能实现
let isDragging = false;
let startX = 0;
let startWidth = 350;

dragHandle.addEventListener('mousedown', (e) => {
  isDragging = true;
  startX = e.clientX;
  startWidth = sidebar.offsetWidth;
  document.documentElement.style.cursor = 'col-resize';
  document.documentElement.style.userSelect = 'none';
});

document.addEventListener('mousemove', (e) => {
  if (!isDragging) return;
  
  const deltaX = startX - e.clientX;
  const newWidth = startWidth + deltaX;
  
  // 设置最小最大宽度限制
  if (newWidth >= 200 && newWidth <= 800) {
    sidebar.style.width = `${newWidth}px`;
  }
});

document.addEventListener('mouseup', () => {
  isDragging = false;
  document.documentElement.style.cursor = '';
  document.documentElement.style.userSelect = '';
});

// 插件后台脚本（background.js）
async function downloadAndInstall(updateUrl) {
  try {
    // 1. 下载插件包
    const zipResponse = await fetch(updateUrl);
    const zipBlob = await zipResponse.blob();

    // 2. 生成临时下载链接
    const blobUrl = URL.createObjectURL(zipBlob);

    // 3. 用浏览器API触发安装
    chrome.runtime.requestUpdateCheck(async (status) => {
      if (status === "update_available") {
        chrome.runtime.reload(); // 重启插件生效
      } else {
        // 手动安装（需用户确认）
        chrome.management.install({
          url: blobUrl,
          hash: await calculateHash(zipBlob) // 哈希校验
        }, () => {
          console.log("更新已安装");
        });
      }
    });
  } catch (error) {
    console.error("安装失败:", error);
    showErrorToUser("更新失败，请手动下载");
  }
}

// 计算文件哈希值（SHA-256）
async function calculateHash(blob) {
  const buffer = await blob.arrayBuffer();
  const hashArray = await crypto.subtle.digest('SHA-256', buffer);
  return Array.from(new Uint8Array(hashArray))
    .map(b => b.toString(16).padStart(2, '0')).join('');
}

function checkUpdate() {
  const currentVersion = chrome.runtime.getManifest().version;

  // 替换成你的Gitee直链
  fetch("https://gitee.com/LuisGaoBH/gccpscfk_ai_plugin/raw/master/version.json")
    .then(response => response.json())
    .then(data => {
      if (data.version > currentVersion) {
        // 提示用户更新
        downloadAndInstall(data.url);
      }
    });
}

// 监听来自右键菜单的消息
window.addEventListener('message', (event) => {
  // 验证消息来源（可选但建议）
  // if (event.source !== winsdow) return;

  // 检查消息类型
  if (event.data.type === 'ASK_KNOWLEDGE_BASE') {
    const selectedText = event.data.text;
    handleSend(selectedText.trim());
  }
  else if (event.data.type === 'UPDATE_PLUGIN') {
    checkUpdate();
  }
});

// 每天检查一次
// 1. 浏览器每次启动时
chrome.runtime.onStartup.addListener(checkUpdate);
// 2. 插件被安装或更新时
chrome.runtime.onInstalled.addListener(checkUpdate);
// 3. 用户主动点击"检查更新"按钮（可选）
chrome.runtime.onMessage.addListener((msg) => {
  if (msg.action === "manualCheck") 
    checkUpdate();
});